<template>
  <div class="filterPanel">
    <div class="page-title">{{filterTitle}}</div>
    <slot></slot>
    <div class="filterArea">
      <div class="filterRow" v-for="rowList in filterRowList">
        <div class="filterItem" v-for="(filter,index) in rowList || []" :key="index">
          <div class="filterContainer" v-if="filter && filter!='btn'">
            <div class="filterTitle">{{filter.title}}</div>
            <div class="filterContent">
              <zy-input v-if="filter.type==='input'" v-model="filter.value" :type="filter.tag"
                        :maxlength="filter.maxlength"
                        :placeholder="filter.placeholder || `请输入${filter.title}`" :clearable="true"></zy-input>
              <el-select v-if="filter.type==='select' || filter.type==='selectMultiple'" v-model="filter.value"
                         filterable placeholder="请选择" :multiple="filter.type==='selectMultiple'" collapse-tags>
                <el-option v-for="option in filter.optionList" :key="option.value" :label="option.label"
                           :value="option.value"></el-option>
              </el-select>
              <datePicker v-if="filter.type==='date'" v-model="filter.value" :type="filter.dateType" :rangeType="filter.rangeType"></datePicker>
              <el-cascader v-if="filter.type==='cascader' && filter.optionProps" v-model="filter.value"
                           :options="filter.optionList" ref="filterCascader"
                           @change="changeVal(filter.optionProps.checkStrictly)"
                           :props="{ checkStrictly: filter.optionProps.checkStrictly, value: filter.optionProps.value || 'value', label: filter.optionProps.label || 'label', children: filter.optionProps.children || 'children' }"
                           filterable :show-all-levels="false"></el-cascader>
            </div>
          </div>
          <div class="btnArea" v-if="filter && filter=='btn'">
            <zy-button @click="submitFilter(true)" class="filterBtn">重置</zy-button>
            <layout-dropdown class="dropdown-box filterBtn" :dropdown-list="filterSelfList" :is-filter="true"
                             @dropdownChange="dropdownChange" :min-column="minColumn"
                             v-if="isShowDrop"></layout-dropdown>
            <zy-button @click="submitFilter(false)" class="filterBtn" :type="`primary`">查询</zy-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
	import datePicker from "../datePicker/index"

	export default {
		name: "filterPanel",
		props: {
			//是否需要调整布局下拉
			isShowDrop: {
				type: Boolean,
				default: () => true
			},
			alignItem: {
				type: String,
				default: () => 'right'
			},
			labelWidth: {
				type: String,
				default: () => ''
			},
			//标题
			filterTitle: {
				type: String,
				default: ''
			},
			// 筛选面板名称（务必保证此名称唯一，此名称用于缓存筛选面板的展示数据）
			filterName: {
				type: String,
				default: () => ''
			},
			/**
			 * 筛选列表
			 * 示例参数 {          （todo 暂时列出目前所需要的参数，若有新增待后续补充   2021/01/21 zf）
			 *   filterTitle: ''   筛选参数标题 (必传)
			 *   filterName: ''    筛选参数名称 (必传)
			 *   value: ''         筛选参数值 (必传)
			 *   type: ''          筛选参数类型 (必传)  目前支持类型  'input'(输入类型)  'date'(单个时间类型) 'daterange'(时间区间类型) 'select'(下拉选择类型) 'valueRange'(区间范围类型) 'cascader'(级联菜单类型)
			 *   optionProps: []   类型为cascader时必传 cascader的参数
			 *   optionList: []    筛选下拉列表 类型为'select' 和 'cascader'时必传
			 *   isSelected: true  是否选中参数，用于调整筛选参数的展示（选传）
			 * }
			 */
			filterList: {
				type: Array,
				default: () => []
			},
			maxRowLength: {
				type: Number,
				default: () => 4
			},
			minColumn: {
				type: Number,
				default: () => 2
			}
		},
		data() {
			return {
				isShow: false,
				form: {},
				filterRowList: [],
				filterSelfList: [],
			};
		},
		computed: {},
		watch: {
			filterList: {
				handler(newVal) {
					let filterList = [];
					this.filterSelfList.forEach(item => {
						newVal.forEach(newItem => {
							if (item.name === newItem.name) {
								filterList.push(
									{
										...newItem,
										isSelected: item.isSelected
									}
								);
							}
						})
					});
					this.filterSelfList = JSON.parse(JSON.stringify(filterList));
				},
				deep: true
			},
			filterSelfList: {
				handler(newVal) {
					this.filterRowListHandle(newVal);
				},
				deep: true
			}
		},
		components: {
			datePicker,
		},
		methods: {
			filterRowListHandle(newVal) {
				let filterRowList = [], filterList = JSON.parse(JSON.stringify(newVal)), list = [], childList = [];

				filterList.forEach(item => {
					if (item.isSelected) {
						list.push(item);
					}
				});

				list.forEach((item, index) => {
					if ((index + 1) % this.maxRowLength !== 0) {
						childList.push(item);
					} else {
						childList.push(item);
						filterRowList.push(childList);
						childList = [];
					}
				});

				if (childList.length) {
					filterRowList.push(childList);
				}

				if (filterRowList[filterRowList.length - 1].length % this.maxRowLength !== 0) {
					filterRowList[filterRowList.length - 1][this.maxRowLength - 1] = 'btn';
				} else {
					filterRowList[filterRowList.length] = [];
					filterRowList[filterRowList.length - 1][this.maxRowLength - 1] = 'btn';
				}

				this.filterRowList = filterRowList;
			},
			changeTimeValue(obj) {
				this.filterList[obj.index].value = obj.val;
			},
			submitFilter(isReset) {
				let form = {};
				if (isReset) {
					let arr = ['valueRange', 'selectMultiple', 'cascader'];
					let filterRowList = this.filterList.filter(filter => {
						if (arr.includes(filter.type)) {
							filter.value = [];
						} else if (filter.type == 'date' || filter.type == 'daterange') {
							filter.value = filter.defaultVal || []
						} else {
							filter.value = ''
						}
						form[filter.name] = filter.value;
						return filter;
					});
					this.filterRowListHandle(filterRowList);
					form.page_start = 1;
					form.page_size = 10
				} else {
					this.filterRowList.forEach(item => {
						item.forEach(subItem => {
							if (subItem && subItem !== 'btn') {
								form[subItem.name] = subItem.value;
							}
						})
					});
					form.page_start = 1;
				}
				this.$emit('filterChange', form)
			},
			dropdownChange(hideList) {
				let filterList = this.filterSelfList.filter(item => {
					item.isSelected = hideList.indexOf(item.name) === -1;
					return item;
				});
				localStorage.setItem(this.filterName, JSON.stringify(filterList))
			},
			changeVal(checkStrictly) {
				if (checkStrictly) {
					this.$refs.filterCascader[0].dropDownVisible = false;
				}
			},
		},
		mounted() {
			// let filterList = JSON.parse(localStorage.getItem(this.filterName)) || [];
			// if (filterList && filterList.length) {
			// 	this.filterSelfList = JSON.parse(JSON.stringify(filterList));
			// } else {
				this.filterSelfList = JSON.parse(JSON.stringify(this.filterList)).filter(item => {
					item.isSelected = typeof (item.isSelected) === 'boolean' ? item.isSelected : true;
					return item;
				});
			// }
			this.filterRowListHandle(this.filterSelfList);
		},
		created() {
		}
	}
</script>

<style scoped lang="less">
  @import "../../style/common/base.less";

  @boxShadowColor: rgba(0, 0, 0, 0.1);

  .filterPanel {
    border-radius: @commonBorderRadius;
    padding: @commonPaddingOutside;
    margin-bottom: 12px;
    background: @allWhite;
    box-shadow: 0px 0px 4px 0px @boxShadowColor;

    .page-title {
      font-size: 16px;
      font-weight: bold;
      color: @fontColor;
      margin-bottom: 16px;
      position: relative;

      &:after {
        content: '';
        position: absolute;
        top: 0;
        bottom: 0;
        left: -@commonPaddingOutside;
        width: 4px;
        background: @allWarringColor;
      }
    }

    .filterArea {
      .filterRow {
        display: flex;
        justify-content: space-between;
        margin-top: 12px;

        .filterItem {
          width: 312px;

          .filterContainer {
            display: flex;
            align-items: center;

            .filterTitle {
              display: flex;
              justify-content: flex-end;
              font-size: 14px;
              line-height: 20px;
              min-width: 56px;
              margin-right: 16px;
              color: @fontColor;
            }

            .filterContent {
              flex: auto;
              display: flex;
              align-items: center;
              padding-right: 10px;

              .el-input, .el-select, .el-cascader {
                width: 100%;
                height: 40px;

                input {
                  background: rgba(216, 216, 216, 0);
                  border-radius: 4px;
                  border: 1px solid #C7CBD1;
                }
              }
            }
          }
        }
      }
    }

    .btnArea {
      flex: auto;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .filterBtn {
        margin-right: 12px;

        &:last-child {
          margin-right: 0;
        }
      }
    }

    /deep/ .date-picker .el-date-editor.el-input__inner {
      width: 100%;

      .el-range-input {
        flex: 1;
      }

      .el-input__icon {
        display: none;
      }
    }
  }

  @media screen and (max-width: 1440px) {
    .filterPanel {
      padding: 24px 12px;
    }

    .filterPanel .filterArea .filterRow .filterItem {
      width: 267px;
    }

    .filterPanel .filterArea .filterRow .filterItem .filterContainer .filterTitle {
      margin-right: 8px;
    }
  }

</style>
